package com.hanbang.cxgz_2.view.about_me.activity;

import android.content.Intent;
import android.support.design.widget.TextInputLayout;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hanbang.audiorecorder.RecordActivity;
import com.hanbang.cxgz_2.R;
import com.hanbang.cxgz_2.appliction.MyApplication;
import com.hanbang.cxgz_2.appliction.base.baseadapter.ViewHolder;
import com.hanbang.cxgz_2.appliction.base.baseadapter.abslistview.CommonAdapter;
import com.hanbang.cxgz_2.appliction.base.view.activity.BaseMvpActivity;
import com.hanbang.cxgz_2.mode.javabean.jianghu.EsotericZhuFuLiaoData;
import com.hanbang.cxgz_2.mode.javabean.other.CaiXiData;
import com.hanbang.cxgz_2.pressenter.about_me.IssuerEsoteric_k_Presenter;
import com.hanbang.cxgz_2.utils.http.GlideUtils;
import com.hanbang.cxgz_2.utils.other.EditHelper;
import com.hanbang.cxgz_2.utils.other.FileUtils;
import com.hanbang.cxgz_2.utils.other.MediaFile;
import com.hanbang.cxgz_2.utils.other.Validators;
import com.hanbang.cxgz_2.utils.ui.AndroidBug5497Workaround;
import com.hanbang.cxgz_2.utils.ui.SnackbarUtil;
import com.hanbang.cxgz_2.utils.ui.ToastUtils;
import com.hanbang.cxgz_2.utils.ui.UiUtils;
import com.hanbang.cxgz_2.view.about_me.iview.IssuerEsoteric_K_View;
import com.hanbang.cxgz_2.view.other.PhotoActivity;
import com.hanbang.cxgz_2.view.widget.GridViewForScrollView;
import com.hanbang.cxgz_2.view.widget.IssuerEsotericAddMaterial;
import com.hanbang.cxgz_2.view.widget.PopupSelect;
import com.hanbang.cxgz_2.view.widget.dialog.DialogProgress;
import com.hanbang.cxgz_2.view.widget.dialog.DialogSelectMode;
import com.hanbang.cxgz_2.view.widget.media.MusicPlayView;
import com.hanbang.cxgz_2.view.widget.media.VideoPlayView;
import com.hanbang.videoplay.view.VideoCameraActivity;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;


/**
 * 作者　　: 杨阳
 * 创建时间: 2016/9/2 10:44
 * 邮箱　　：360621904@qq.com
 * <p>
 * 功能介绍：开放秘籍上传页面
 */

public class IssuerEsoteric_K_Activity extends BaseMvpActivity<IssuerEsoteric_K_View, IssuerEsoteric_k_Presenter> implements IssuerEsoteric_K_View {

    @BindView(R.id.find_uploading_k_activity_root)
    RelativeLayout viewRoot;
    @BindView(R.id.haiBao)
    ImageView haiBao;
    @BindView(R.id.esotericName)
    TextInputLayout esotericName;
    @BindView(R.id.maiDian)
    TextInputLayout maiDian;
    @BindView(R.id.teDian)
    TextInputLayout teDian;
    @BindView(R.id.caiXi)
    TextView caiXi;
    @BindView(R.id.editText)
    EditText editText;
    @BindView(R.id.describe)
    TextInputLayout describe;
    @BindView(R.id.zhuLiao)
    IssuerEsotericAddMaterial zhuLiao;
    @BindView(R.id.fuLiao)
    IssuerEsotericAddMaterial fuLiao;
    @BindView(R.id.attenteon)
    TextInputLayout attenteon;
    @BindView(R.id.inputPrice)
    TextInputLayout inputPrice;
    //视频路径
    private String videoPlayPath;
    @BindView(R.id.find_uploading_k_activity_videoPlay)
    VideoPlayView videoPlay;
    //音频路径
    private String musicPlayPath;
    @BindView(R.id.music_play)
    MusicPlayView musicPlay;
    //显示过程图片
    @BindView(R.id.showProcessPicture)
    GridViewForScrollView showProcessPicture;
    //过程图片路径
    private ArrayList<String> processPicturePhat = new ArrayList<>();
    //海报路径
    private String haiBaoPath;
    private EditHelper editHelper = new EditHelper(this);

    private ArrayList<EsotericZhuFuLiaoData> zhuLiaoDatas = new ArrayList<>();
    private ArrayList<EsotericZhuFuLiaoData> fuLiaoDatas = new ArrayList<>();
    private int caiXiId;

    @Override
    public int getContentView() {
        return R.layout.activity_uploading_k_activity;
    }


    @Override
    public void clearData() {

    }

    @Override
    public IssuerEsoteric_k_Presenter initPressenter() {
        return new IssuerEsoteric_k_Presenter();
    }

    @Override
    public void initView() {
        AndroidBug5497Workaround androidBug5497Workaround = AndroidBug5497Workaround.assistActivity(this);
        viewRoot.setPadding(0, UiUtils.getStatusHeight(this) - 2, 0, 0);
        toolbar.setBack(this);
        toolbar.setTitle("上传开放式秘籍");

        processPicturePhat.add("");
        showProcessPicture.setAdapter(adapter);
        musicPlay.setVisibility(View.GONE);
        videoPlay.setVisibility(View.GONE);

        editHelper.addEditHelperData(new EditHelper.EditHelperData(esotericName, Validators.getLengthSRegex(1, 20), "请输入秘籍名称"));
        editHelper.addEditHelperData(new EditHelper.EditHelperData(maiDian, Validators.getLengthSRegex(1, 100), "请输入卖点特色"));
        editHelper.addEditHelperData(new EditHelper.EditHelperData(teDian, Validators.getLengthSRegex(1, 100), "请输入特点"));
        editHelper.addEditHelperData(new EditHelper.EditHelperData(describe, Validators.getLengthSRegex(1, 200), "请输入工艺流程描述"));
        editHelper.addEditHelperData(new EditHelper.EditHelperData(attenteon, Validators.getLengthSRegex(1, 100), "请输入工艺流程描述"));
        editHelper.addEditHelperData(new EditHelper.EditHelperData(inputPrice, Validators.getLengthSRegex(1, 7), "请输入价格"));

        zhuLiao.setOnClickCallback(new IssuerEsotericAddMaterial.OnClickCallback() {
            @Override
            public void onClick(ArrayList<EsotericZhuFuLiaoData> datas) {
                zhuLiaoDatas = datas;
            }
        });

        fuLiao.setOnClickCallback(new IssuerEsotericAddMaterial.OnClickCallback() {
            @Override
            public void onClick(ArrayList<EsotericZhuFuLiaoData> datas) {
                fuLiaoDatas = datas;
            }
        });


    }


    @Override
    public int getStatusBarPaddingTop() {
        return 0;
    }

    @Override
    public int getStatusBarResource() {
        return R.color.yellow_top;
    }

    @Override
    public void parseIntent(Intent intent) {

    }

    CommonAdapter adapter = new CommonAdapter<String>(this, R.layout.item_photo_select, processPicturePhat) {
        @Override
        public void convert(final ViewHolder holder, String item) {

            if (holder.getmPosition() == processPicturePhat.size() - 1) {
                holder.setVisible(R.id.item_photo_selectDelete, false);
                //因为有缓存所以增加延时加载
                holder.getView(R.id.item_photo_selectDelete).postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        holder.setImageResource(R.id.item_photo_selectImage, R.mipmap.my_release_ico_addpic);
                    }
                }, 100);


            } else if (!TextUtils.isEmpty(item)) {
                holder.setImageBitmap(R.id.item_photo_selectImage, item);
                holder.setVisible(R.id.item_photo_selectDelete, true);
            }

            holder.setOnClickListener(R.id.item_photo_selectImage, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (processPicturePhat.size() - 1 == holder.getmPosition()) {

                        processPicturePhat.remove(processPicturePhat.size() - 1);
                        MultiImageSelector.create()
                                .showCamera(true)
                                .count(9)
                                .multi()
                                .origin(processPicturePhat)
                                .start(IssuerEsoteric_K_Activity.this, REQUEST_CODE + 1);
                    } else {

                        if (processPicturePhat.size() > 9) {
                            processPicturePhat.remove(processPicturePhat.size() - 1);
                        }
                        PhotoActivity.startUI(IssuerEsoteric_K_Activity.this, processPicturePhat, holder.getmPosition());
                    }
                }
            });

            holder.setOnClickListener(R.id.item_photo_selectDelete, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    processPicturePhat.remove(holder.getmPosition());
                    notifyDataSetChanged();
                }
            });
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //获取海报路径
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            haiBaoPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT).get(0);
            GlideUtils.show(haiBao, haiBaoPath);
        }
        //过程图片路径
        if (requestCode == REQUEST_CODE + 1 && resultCode == RESULT_OK) {
            processPicturePhat.clear();
            processPicturePhat.addAll(data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT));
            processPicturePhat.add("");
            adapter.notifyDataSetChanged();
        }

        //获取音频路径
        if (requestCode == REQUEST_CODE + 2 && resultCode == RESULT_OK) {
            musicPlayPath = FileUtils.getFileSelectPath(data);
            if (!MediaFile.JudgeFileType(musicPlayPath, "mp3")) {
                ToastUtils.getToastShort("请选择MP3,WMA格式的音频文件");
                return;
            }
            musicPlay.setFilePath(musicPlayPath);
            musicPlay.setVisibility(View.VISIBLE);
        }
        //获取视频路径
        if (requestCode == REQUEST_CODE + 3 && resultCode == RESULT_OK) {
            videoPlayPath = FileUtils.getFileSelectPath(data);
            if (!MediaFile.JudgeFileType(videoPlayPath, "mp4")) {
                ToastUtils.getToastShort("请选择MP4格式的视频文件");
                return;
            }
            videoPlay.setUpDefault(videoPlayPath, "本地视频");
            videoPlay.setThumbRes(R.mipmap.logo);
            videoPlay.setVisibility(View.VISIBLE);

        }


        //录制视频路径
        if (requestCode == REQUEST_CODE + 4 && resultCode == RESULT_OK) {
            videoPlayPath = data.getStringExtra(VideoCameraActivity.RESULT);
            videoPlay.setUpDefault(videoPlayPath, "录制视频");
            videoPlay.setThumbRes(R.mipmap.logo);
            videoPlay.setVisibility(View.VISIBLE);
        }

        //录制音频路径
        if (requestCode == REQUEST_CODE + 5 && resultCode == RESULT_OK) {
            musicPlayPath = data.getStringExtra(RecordActivity.MP3PATH);
            musicPlay.setFilePath(musicPlayPath);
            musicPlay.setVisibility(View.VISIBLE);
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        if (musicPlay != null) {
            musicPlay.pause();

        }
        if (videoPlay != null) {
            videoPlay.pause();
        }


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (musicPlay != null) {
            musicPlay.release();
        }

        if (viewRoot != null) {
            videoPlay.release();
        }


    }

    @OnClick({R.id.selectHaiBao, R.id.commit, R.id.selectAudio, R.id.selectVideo, R.id.caiXi_select})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.selectHaiBao:
                MultiImageSelector.create()
                        .showCamera(true)
                        .single()
                        .start(this, REQUEST_CODE);
                break;
            case R.id.commit:
                if (editHelper.check()) {
                    if (TextUtils.isEmpty(haiBaoPath)) {
                        SnackbarUtil.showShort(this, "海报不能为空", SnackbarUtil.Warning).show();
                        return;
                    }
                    if (zhuLiaoDatas.size() == 0) {
                        SnackbarUtil.showShort(this, "主料不能为空", SnackbarUtil.Warning).show();
                        return;
                    }
                    if (fuLiaoDatas.size() == 0) {
                        SnackbarUtil.showShort(this, "辅料不能为空", SnackbarUtil.Warning).show();
                        return;
                    }

                    if (TextUtils.isEmpty(caiXi.getText().toString())) {
                        SnackbarUtil.showShort(this, "请选择菜系", SnackbarUtil.Warning).show();
                        return;
                    }


                    /**
                     * //上传开放式秘籍
                     * type:类型，1为开放式，2为买断式
                     * title:秘籍名称
                     * tedian:特点
                     * maidiantese:卖点特色
                     * price:价格，免费的传0
                     * cuisines_id:菜系，这个在效果图上没有体现出来，需要加上去的
                     * img_url:主图，秘籍效果图，一张">url:主图，秘籍效果图，一张
                     * shipin:视频，可选
                     * <p>
                     * 开放式需要传的参数:
                     * zhuliao:主料，格式为:（名称:数量|名称:数量）
                     * fuliao:辅料，格式为:（名称:数量|名称:数量）
                     * gongyiliucheng:工艺流程
                     * zhuyishixiang:注意事项
                     * img_guocheng:过程图片，可为多张
                     * AudioUrl:音频文件
                     */
                    presenter.getHttpData(
                            String.valueOf(1),
                            editHelper.getText(R.id.esotericName),
                            editHelper.getText(R.id.teDian),
                            editHelper.getText(R.id.maiDian),
                            editHelper.getText(R.id.inputPrice),
                            String.valueOf(caiXiId),
                            haiBaoPath,
                            videoPlayPath,
                            zhuLiaoDatas,
                            fuLiaoDatas,
                            editHelper.getText(R.id.describe),
                            editHelper.getText(R.id.attenteon),
                            processPicturePhat,
                            musicPlayPath
                    );
                }

                break;
            case R.id.selectAudio:
                final DialogSelectMode dialog = new DialogSelectMode(IssuerEsoteric_K_Activity.this, "录音", "选择音频");
                dialog.show();
                dialog.setClickCallback(new DialogSelectMode.OnClickCallback() {
                    @Override
                    public void onClick(int type) {
                        if (type == 1) {
                            RecordActivity.startUi(IssuerEsoteric_K_Activity.this, REQUEST_CODE + 5, MyApplication.appSDFilePath);
                            dialog.dismiss();
                        } else if (type == 2) {
                            UiUtils.startFileSelect(IssuerEsoteric_K_Activity.this, "audio/*", REQUEST_CODE + 2);
                            dialog.dismiss();
                        } else if (type == 0) {
                            dialog.dismiss();
                        }
                    }
                });
                break;
            case R.id.selectVideo:
                final DialogSelectMode dialog2 = new DialogSelectMode(IssuerEsoteric_K_Activity.this, "录制", "选择视频");
                dialog2.show();
                dialog2.setClickCallback(new DialogSelectMode.OnClickCallback() {
                    @Override
                    public void onClick(int type) {
                        if (type == 1) {
                            VideoCameraActivity.startActivity(IssuerEsoteric_K_Activity.this, MyApplication.appSDFilePath, IssuerEsoteric_K_Activity.this.REQUEST_CODE + 4);
                            dialog2.dismiss();
                        } else if (type == 2) {
                            UiUtils.startFileSelect(IssuerEsoteric_K_Activity.this, "video/*", REQUEST_CODE + 3);
                            dialog2.dismiss();
                        } else if (type == 0) {
                            dialog2.dismiss();
                        }
                    }
                });
                break;
            case R.id.caiXi_select:

                presenter.getCaiXiData(false);


                break;
        }
    }


    @Override
    public void upLoading(boolean whetherSucceed) {

    }

    DialogProgress dialogProgress;

    @Override
    public void upLoading(int progress, boolean done, boolean isUpdate, boolean isCompress) {
        if (dialogProgress == null) {
            dialogProgress = new DialogProgress(this);
        }
        dialogProgress.setTitleText(isCompress ? "压缩中" : "上传中");
        dialogProgress.setProgress(progress);
        dialogProgress.show();
    }

    @Override
    public void dismissProgressDialog() {
        if (dialogProgress != null && dialogProgress.isShowing()) {
            dialogProgress.dismiss();
        }
    }

    PopupSelect popupSelect;

    @Override
    public void getCaiXiData(ArrayList<CaiXiData> datas) {
        if (popupSelect == null) {
            popupSelect = new PopupSelect(IssuerEsoteric_K_Activity.this, datas, 8, 100);
        }

        popupSelect.showPopupWindow(caiXi);
        popupSelect.setOnClickCallback(new PopupSelect.OnClickCallback() {
            @Override
            public void onClick(int id, String content, int type) {
                caiXi.setText(content);
                caiXiId = id;
            }
        });


    }
}
